package com.nondo.rdp.finance.endpoint.api.admin.setting.user;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.auth.interceptor.OperationLog;
import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.model.UserEditBeanInner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController("apiAdminSettingUser")
@RequestMapping("/api/admin/setting/user")
public class UserEndpoint {
    @Autowired
    UserService userService;

    @Autowired
    private PasswordEncoder encoder;

    @RequestMapping(value = "/info")
    public View findOne(HttpServletRequest request, HttpServletResponse response) {
        View view = new View(20000, "获取成功");
        User user = UserUtils.getUser(request, response);

        Map map = new HashMap();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("nickName", user.getNickName());
        map.put("avatar", user.getAvatar());

        view.setData(map);

        return view;
    }

    @OperationLog
    @RequestMapping(value = "/update")
    public View update(@RequestBody UserEditBeanInner userRequest, HttpServletRequest request, HttpServletResponse response) {
        View view = new View(20000, "修改成功");

        User user = UserUtils.getUser(request, response);

        //处理昵称
        user.setNickName(userRequest.getNickName());
        //处理头像
        if (!user.getAvatar().equals(userRequest.getAvatar())) {
            user.setAvatar(userRequest.getAvatar());
        }
        //处理密码
        if (userRequest.getPassword() != null) {
            if (userRequest.getPassword().equals(userRequest.getPassword_confirm())) {
                String pwd = encoder.encode(userRequest.getPassword());
                user.setPassword(pwd);
                view.setData(true);
            } else {
                return View.ofError("两次输入的密码不匹配");
            }
        }
        this.userService.save(user);

        return view;
    }
}